/*
 * @Author: Nick
 * @Date: 2021-04-26 16:58:11
 * @LastEditTime: 2021-06-04 16:24:23
 * @LastEditors: Nick
 * @Description: In User Settings Edit
 * @FilePath: /emotech-weapp/src/utils/index.js
 */
import Taro from '@tarojs/taro'
import { authSetting } from '@/utils/config'
import { set as setGlobalData } from '@/utils/global_data'

/**
 * @description: 获取微信的 code
 * @return {*} code
 */
export const getLoginCode = async () => {
  return await new Promise((resolve, reject) => {
    Taro.login({
      success: (res) => {
        console.log(res, '获取 code')
        if (res.code && res.errMsg === "login:ok") {
          setGlobalData('code', res.code)
          resolve(res.code)
        } else {
          reject(res)
        }
        resolve(res)
      },
      fail: (err) => reject(err),
    })
  })
}

// TODO 下面还暂时未用到

/**
 * @description: 获取设备信息
 * @return {*} 设备信息
 */
export const getSystemInfo = () => {
  return new Promise((resolve, reject) => {
    Taro.getSystemInfo({
      success: (res) => {
        resolve(res)
      },
      fail: (err) => reject(err),
    })
  })
}

/**
 * @description: 获取用户信息
 * @return {*} resolve(用户信息)
 */
export const getUserProfile = async () => {
  return await new Promise((resolve, reject) => {
    // eslint-disable-next-line no-undef
    wx.getUserProfile({
      desc: '用于完善用户资料',
      success: (res) => resolve(res),
      fail: (err) => reject(err),
    })
  })
}

/**
 * @description: 设置未登录状态的图片大小
 * @return {*} 动态计算的图片大小
 */
export const notLoginImageAuto = async (_this, dom) => {
  return new Promise((resolve, reject) => {
    Taro.createSelectorQuery().in(_this.$scope).select(dom).boundingClientRect().exec(res => {
      try {
        const { height } = res[0]
        const imageHeight = 360, imageWidth = 215
        const windowHeight = height - 90 - 70
        const originRatio = imageWidth / imageHeight
        const viewHeight = windowHeight
        const viewWidth = windowHeight * originRatio
        const unLoginImageSize = { width: viewWidth + 'px', height: viewHeight + 'px' }
        resolve(unLoginImageSize)
        Taro.setStorageSync('unLoginImageSize', unLoginImageSize)
      } catch (error) {
        reject(error)
      }
    })
  })
}

/**
 * rgba转 16进制
 */
export function rgbaToHex(color) {
  var values = color
    .replace(/rgba?\(/, '')
    .replace(/\)/, '')
    .replace(/[\s+]/g, '')
    .split(',')
  var a = parseFloat(values[3] || 1),
    r = Math.floor(a * parseInt(values[0]) + (1 - a) * 255),
    g = Math.floor(a * parseInt(values[1]) + (1 - a) * 255),
    b = Math.floor(a * parseInt(values[2]) + (1 - a) * 255)
  return (
    '#' +
    ('0' + r.toString(16)).slice(-2) +
    ('0' + g.toString(16)).slice(-2) +
    ('0' + b.toString(16)).slice(-2)
  )
}
/**
 * 展示的文本
 * @param {*} title 内容
 * @param {*} icon icon
 * @param {*} duration 显示时长
 */
export async function showToast(title, icon, duration) {
  const res = await Taro.showToast({
    title: title,
    icon: icon || 'none',
    duration: duration | 2000
  })
  return res
}

/** 设置海报的宽高 */
export const setSwiperWidthHeight = async () => {
  const systemInfo = await Taro.getSystemInfo()
  const { windowHeight } = systemInfo
  const imageWidth = 375, imageHeight = 724
  const originRatio = imageWidth / imageHeight
  const height = windowHeight - 200
  const width = height * originRatio
  const option = { width: width, height: height }
  return option
}

/** 加载图片 */
export const loadImage = (canvas, url, option) => {
  return new Promise((resolve, reject) => {
    const img = canvas.createImage()
    img.onload = () => resolve(img)
    img.onerror = () => reject(option)
    img.src = url
  })
}

/**绘制头像 */
export const circleImg = (ctx, img, x, y, r) => {
  ctx.save()
  var d = 2 * r
  var cx = x + r
  var cy = y + r
  ctx.arc(cx, cy, r, 0, 2 * Math.PI)
  ctx.clip()
  ctx.drawImage(img, x, y, d, d)
  ctx.restore()
}

/** 计算用户名称的长度 */
export const userNameLength = (str) => {
  const arr = str.split('');
  let count = 0;
  for (var i = 0; i < arr.length; i++) {
    if (arr[i].charCodeAt(0) < 299) {
      count++
    } else {
      count += 2
    }
    if (count >= 10) {
      const s = arr.slice(0, i + 1).join('') + '...';
      return s
    }
  }
  return arr.join('')
}

/** 检测用户的授权 */
export const checkAuthSetting = async (auth) => {
  return new Promise((resolve, reject) => {
    Taro.authorize({ scope: auth }).then(() => {
      resolve(true)
    }).catch(() => {
      const text = '您未授权' + authSetting[auth] + '将无法体验功能'
      Taro.showModal({
        title: '提示',
        content: text,
        showCancel: true,
        confirmText: '授权',
        confirmColor: '#52a2d8'
      }).then(res => {
        if (res.cancel) {
          console.log(text, '用户点击取消')
          return false
        } else {
          Taro.openSetting().then(() => {
            resolve(true)
          }).catch(() => {
            console.log(text, '用户并未开启授权')
            reject(false)
          })
        }
      }).catch(err => {
        console.log(err, '用户并未开启授权')
      })
    })
  })
}
/** showLoading */
export const showLoading = async (title) => {
  Taro.showLoading({
    title: title || '加载中...'
  })
}

/** hideLoading */
export const hideLoading = async () => {
  Taro.hideLoading()
}